<template>
	<view class="subject1">
		<v-tabs v-if="type != 1" v-model="current" fixed field="name" bold :tabs="tabs" paddingItem="0 12rpx"
			pillsBorderRadius="6rpx" lineHeight="10rpx" fontSize="28rpx" height="60rpx" @change="changeTab"></v-tabs>
		<scroll-view :style="{ 'height': scrollYH }" :scroll-y="true" :show-scrollbar="true"
			:class="type == 0 ? 'scroll-top' : ''">
			<view class="list-box">
				<!-- 练习模式 -->
				<template v-if="type == 0">
					<view class="list-public">
						<text class="list-box-title" style="background-color: #FB5051;">共用劳保物品</text>
						<view class="list-public-box" style="background-color: #FB5051;">
							<uni-row :gutter="10">
								<template v-if="list_data && list_data[0]">
									<uni-col :span="6" class="subject-list" v-for="(item, index) in list_data[0]">
										<view :class="item.select ? 'list-li on' : 'list-li'"
											@click="subClick($event, item, index)">
											<!-- {{item.select}} -->
											<image style="width: 100%; height: 200rpx;" :src="item.img"
												mode="aspectFit">
											</image>
											<text class="img-text">{{ item.text }}</text>
										</view>
									</uni-col>
								</template>
							</uni-row>
						</view>
					</view>
					<view class="list-other" style="margin-top: 20rpx;">
						<text class="list-box-title" style="background-color: #03AAF7;"><text
								:style="type == 0 ? { 'color': '#f00', 'background-color': '#fff', 'fontWeight': '700' } : ''">{{ name }}</text>专用劳保用品</text>
						<view class="list-public-box" style="background-color: #03AAF7;">
							<uni-row :gutter="10">
								<template v-if="list_data && list_data[1]">
									<uni-col :span="6" class="subject-list" v-for="(item, index) in list_data[1]">
										<view :class="item.select ? 'list-li on' : 'list-li'"
											@click="subClick($event, item, index)">
											<!-- {{item.select}} -->
											<image style="width: 100%; height: 200rpx;" :src="item.img"
												mode="aspectFit">
											</image>
											<text class="img-text">{{ item.text }}</text>
										</view>
									</uni-col>
								</template>
							</uni-row>
						</view>
					</view>
				</template>
				<!-- 查看选择 -->
				<template v-if="type == 2">
					<view class="list-other" style="margin-top: 20rpx;">
						<text class="list-box-title" style="background-color: #03AAF7;"><text
								:style="type == 0 ? { 'color': '#f00', 'background-color': '#fff', 'fontWeight': '700' } : ''">{{ list.name }}</text>劳保用品你的选择</text>
						<view class="list-public-box" style="background-color: #03AAF7;">
							<uni-row :gutter="10">
								<uni-col :span="6" class="subject-list" v-for="(item, index) in list_data">
									<view :class="item.select ? 'list-li on' : 'list-li'">
										<view :class="item.state == 0 ? 'subject-err' : 'subject-right'">
											<text v-if="item.state == 0" class="iconfont icon-cuowu"></text>
											<text v-else class="iconfont icon-zhengque"></text>
										</view>
										<image style="width: 100%; height: 200rpx;" :src="item.img" mode="aspectFit">
										</image>
										<text class="img-text">{{ item.text }}</text>
									</view>
								</uni-col>
							</uni-row>
						</view>
					</view>
					<view class="">
						<view class="list-other" style="margin-top: 20rpx;">
							<text class="list-box-title" style="background-color: #f00;"><text
									style="font-weight:700">{{ list.name }}</text>劳保用品正确选择</text>
							<view class="list-public-box" style="background-color: #03AAF7;">
								<uni-row :gutter="10">
									<uni-col :span="6" class="subject-list" v-for="(item, index) in list.correctList">
										<view :class="item.select ? 'list-li on' : 'list-li'">
											<!-- {{item.select}} -->
											<image style="width: 100%; height: 200rpx;" :src="item.img"
												mode="aspectFit">
											</image>
											<text class="img-text">{{ item.text }}</text>
										</view>
									</uni-col>
								</uni-row>
							</view>
						</view>
					</view>
				</template>
				<template v-if="type == 1">
					<view class="list-public">
						<!-- <text class="list-box-title" style="background-color: #FB5051;">共用劳保物品</text> -->
						<view class="list-public-box" style="background-color: #FB5051;">
							<uni-row :gutter="10">
								<uni-col :span="6" class="subject-list" v-for="(item, index) in list">
									<view :class="item.select ? 'list-li on' : 'list-li'"
										@click="subClick($event, item, index)">
										<!-- {{item.select}} -->
										<image style="width: 100%; height: 200rpx;" :src="item.img" mode="aspectFit">
										</image>
										<text class="img-text">{{ item.text }}</text>
									</view>
								</uni-col>
							</uni-row>
						</view>
					</view>
				</template>
			</view>
		</scroll-view>
		<view class="select-box" v-if="type == 1">
			<l-ball ref="ballRef" :img="img" :color="'#f00'" :size="'80rpx'" style="width: 100%;">
				<!-- 可以导出active变量，小球将要达到时，给这购物车加点动画 -->
				<template #default="{ active }">
					<view class="select-box-content">
						<view :class="{ active }" class="select-title">请选择<text
								style="color: #f00;font-weight: 700;">{{ list_question.name }}</text>劳保用品</view>
						<view class="select-list">
							<uni-row :gutter="10">
								<uni-col :span="4" v-for="(item, index) in select_data" class="select-item"
									style="position: relative;">
									<view class="select-img">
										<view class="iconfont icon-cuowu1" @click="delClick(item, index)">
										</view>
										<image style="width: 100%;height: 100rpx;" :src="item.img" mode="aspectFit">
										</image>
										<text style="font-size: 24rpx;">{{ item.text }}</text>
									</view>
								</uni-col>
							</uni-row>
						</view>
						<button @click="submit">提交</button>

					</view>

				</template>
			</l-ball>
		</view>

		<uni-popup ref="popup" type="dialog">
			<uni-popup-dialog type="message" :showClose="false" confirmText="已知晓" title="通知">
				<text style="font-size: 32rpx;">请点击图片选择<text
						style="color: #f00;font-weight: 700;">{{ list_question.name }}</text>劳保用品</text>
			</uni-popup-dialog>
		</uni-popup>

		<uni-popup ref="submitPopup" type="center">
			<view class="submit-popup-box">
				<view class="submitPopupTxt">
					<text class="popup-title">考试成绩</text>
					<view class="popup-sub">
						<text class="submit-name">{{ userInfo.username }}-{{ userInfo.IDcardNum }}</text>
						<text class="submit-type">{{ list_question.name }}</text>
					</view>
					<view class="fraction">总计{{ list_question?.itemIds?.length || 0 }}件
						选对<text :style="getScoreStyle(userlist?.score)" class="fraction-num">{{
							userlist?.rightIds?.length || 0
							}}</text>件
					</view>
					<!-- <text class="timePaper">答题用时：{{ examinationTime }}</text> -->
					<view class="prompt-box">
						<view style="background: #f00;color: #fff;" class="prompt-box-txt">
							<text>选错</text>
							<text>{{ userlist?.errIds?.length || 0 }}</text>
						</view>
						<view style="background: #329cfe;color: #fff;" class="prompt-box-txt">
							<text>选对</text>
							<text>{{ userlist?.rightIds?.length || 0 }}</text>
						</view>
						<view v-if="userlist?.noneIds?.length > 0" style="background-color: #b1b1b1;color: #fff;"
							class="prompt-box-txt">
							<text>未选</text>
							<text>{{ userlist?.noneIds?.length || 0 }}</text>
						</view>
					</view>
					<view class="submit-list">
						<button size="mini" @click="practiceError" class="list-btn" type="warn">错题练习</button>
						<!-- <button size="mini" @clic="lockpaper" class="list-btn" type="primary">查看试卷</button> -->
						<button @click="closeBlack" size="mini" class="list-btn" type="default">关 闭</button>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import {
	deepClone
} from '@/utils/tools'
import {
	getSubOnePaper,
	getSubOnePaperDetail,
	addSubOnePaper
} from '@/http/question.js'
export default {
	data() {
		return {
			id: null,
			current: 0,
			list: [],
			img: '',
			data: [],
			select_data: [],
			scrollYH: null,
			tabStyle: 'font-size:26rpx',
			tabs: [],
			list_question: {
				itemIds: [],
				name: ''
			},
			list_submit: {
				name: '氩弧焊用品',
				user_list_id: [1, 2, 3, 4, 5, 6, 7, 8, 9],
				list_id: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14],
				score: ''
			},
			type: 0, //0 练习模式 1模拟考试 2查看选择
			nav_index: null,
			list_data: [[], []],
			name: '全部',
			userlist: {
				rightIds: [],
				errIds: [],
				noneIds: [],
				score: 0
			},
			userInfo: {},
			opcName: '',
			startTime: '',
			select_list: [], // 错题模式-用户选择的
			correct_list: [], // 错题模式-正确的
		}
	},
	async onLoad(val) {
		console.log(val);
		if (val.hasOwnProperty('id')) {
			this.id = val.id
			this.model = val.model
			uni.setNavigationBarTitle({
				title: val.model == 1 ? '错题练习' : '试卷查看'
			})
			this.type = 2
		} else {
			this.type = val.type // type 0 练习模式 1 模拟考试
		}
		this.userInfo = uni.getStorageSync('userinfo')
		this.opcName = uni.getStorageSync('opcName')
		const data = await this.loadData()
		if (this.type == 0) {
			this.list = data
			let all = {
				"id": 0,
				"name": "全部",
				"item": []
			}
			const groupedData = this.list.list.reduce((acc, item) => {
				if (!acc[item.share]) {
					acc[item.share] = [];
				}
				acc[item.share].push(item);
				return acc;
			}, {});
			// 将对象的值（即分组数组）转换为一个数组的数组  
			const transformedData = Object.values(groupedData).map(group => {
				// 对每个分组内的项目按 sort 属性排序  
				return group.sort((a, b) => a.sort - b.sort);
			});
			this.list.class.unshift(all)
			this.data = deepClone(transformedData) // 原始数据
			this.list_data = deepClone(transformedData)
			this.$nextTick(() => {
				this.tabs = this.list.class
			})

			// this.data = deepClone(this.list)
		}
		if (this.type == 1) {
			//.sort(() => Math.random() - 0.5);
			this.startTime = new Date()
			this.list = data.list
			this.$refs.popup.open()
			this.$nextTick(async () => {
				try {
					let dom = await this.queryAndSetHeight('.select-box');
					this.scrollYH = Math.round(dom.top) + 'px';
				} catch (error) {
					console.error('获取高度时出错:', error);
				}
			});
			this.select_index = Math.floor(Math.random() * 4)
			this.list_question = data.class[this.select_index]
		}
		if (this.type == 2) {
			// this.data = data
			let list_data = {
				...data,
				correctList: data.noneList.concat(data.rightList), // 正确的

			}
			list_data.correctList = list_data.correctList.sort((a, b) => a.id - b.id)
			// 更新userList中的状态  
			this.updateStateInUserList(list_data.userList, list_data.errList, 0); // 对于errList中的元素，设置state为0
			this.updateStateInUserList(list_data.userList, list_data.rightList, 1); // 对于rightList中的元素，也设置state为1
			this.list = list_data
			this.list_data = list_data.userList
			this.tabs = [{
				"id": 0,
				"name": "已选"
			}, {
				"id": 1,
				"name": "选对"
			}, {
				"id": 2,
				"name": "选错"
			}, {
				"id": 3,
				"name": "未选"
			}]
		}
	},
	methods: {
		updateStateInUserList(userList, targetList, state) {
			const targetIds = new Set(targetList.map(item => item.id)); // 将ID转换为Set，以便快速查找  

			userList.forEach(user => {
				if (targetIds.has(user.id)) {
					user.state = state; // 更新状态  
				}
			});
		},
		async loadData() {
			let params = {
				type: 0
			}
			return new Promise((resolve, reject) => {
				if (this.id == undefined) {
					getSubOnePaper(params).then(res => {
						// console.log(res);  
						// Assuming `res` contains the actual data you want to resolve with  
						const data = res; // Save the response data to a local variable  

						// Resolve with the data retrieved from the API call  
						resolve(data.data);
					}).catch(error => {
						// Handle the error and make sure the Promise is rejected  
						reject(error);
					});
				} else {
					params = {
						id: this.id
					}
					getSubOnePaperDetail(params).then(res => {
						// console.log(res);  
						// Assuming `res` contains the actual data you want to resolve with  
						const data = res; // Save the response data to a local variable  

						// Resolve with the data retrieved from the API call  
						resolve(data.data);
					}).catch(error => {
						// Handle the error and make sure the Promise is rejected  
						reject(error);
					});
				}

			});
		},
		subClick(e, item, indexd) {
			if (this.type == 0) {
				return
			}
			this.img = item.img
			let index = this.select_data.findIndex(i => i.id == item.id)
			this.select_index = indexd
			if (this.list[this.select_index].select) {
				return
			} else {
				this.$nextTick(async () => {
					try {
						this.$refs.ballRef.action(e)
						this.list[this.select_index].select = true
						this.select_data.push(item)
						setTimeout(async () => {
							this.$nextTick();
							let dom = await this.queryAndSetHeight('.select-box');
							this.scrollYH = Math.round(dom.top) + 'px'
						}, 50)
					} catch (error) {
						console.error('获取高度时出错:', error);
					}
				})
			}
		},
		async delClick(item, index) {
			try {
				this.select_index = index
				let indexd = this.list.findIndex(e => e.id === item.id)
				let del_index = this.select_data.findIndex(e => e.id === item.id)
				this.select_data.splice(del_index, 1)
				this.list[indexd].select = false
				setTimeout(async () => {
					this.$nextTick();
					let dom = await this.queryAndSetHeight('.select-box');
					this.scrollYH = Math.round(dom.top) + 'px'
				}, 50)
			} catch (error) {
				console.error('获取高度时出错:', error);
			}
		},
		queryAndSetHeight(selector) {
			return new Promise((resolve, reject) => {
				const query = uni.createSelectorQuery().in(this);
				query.select(selector)
					.boundingClientRect(rect => {
						if (rect) {
							resolve(rect);
						} else {
							reject(new Error('无法获取DOM元素的高度'));
						}
					}).exec();
			});
		},
		changeTab(item) {
			console.log(item, this.type);
			let tabData
			if (this.type == 2) {
				tabData = this.tabs[item]
				// id 0 已选 1 对 2错 3未选  4正确的
				if (tabData.id == 0) {
					this.list_data = this.list.userList
				}
				if (tabData.id == 1) {
					this.list_data = this.list.rightList
				}
				if (tabData.id == 2) {
					this.list_data = this.list.errList.map(e => {
						return {
							...e,
							state: 0
						}
					})
				}
				if (tabData.id == 3) {
					this.list_data = this.list.noneList.map(e => {
						return {
							...e,
							state: 2
						}
					})
				}

				return
			}
			let data = deepClone(this.data)
			tabData = this.tabs[item]
			this.name = tabData.name
			if (tabData.name == '全部') {
				this.list_data[1] = data[1]
				return
			}
			let commonElements = data[1].filter(obj1 => {
				return tabData.itemIds.some(obj2 => obj2 === obj1.id);
			});
			this.list_data[1] = commonElements

		},
		closeBlack() {
			uni.navigateBack()
		},
		practiceError() {
			uni.redirectTo({
				url: `/pages/question/subject1?id=${this.id}&model=1`
			})
		},
		transformData(expectedIds, items) {
			const errIds = [];
			const rightIds = [];
			const noneIds = [];
			const userId = [];
			const idsFromItems = new Set(items.map(item => item.id));

			expectedIds.forEach(id => {
				if (!idsFromItems.has(id)) {
					noneIds.push(id);
				} else if (items.some(item => item.id === id && item.select)) {
					rightIds.push(id);
					userId.push(id);
				}
			});

			items.forEach(item => {
				if (item.select && !rightIds.includes(item.id)) {
					errIds.push(item.id);
					userId.push(item.id);
				}
			});

			return {
				errIds,
				rightIds,
				noneIds,
				score: rightIds.length,
				userIds: [...new Set(userId)], // 使用Set去重，然后转换回数组  
			};
		},
		submit() {
			if (!this.list_question?.itemIds) {
				console.warn('list_question.itemIds 未定义')
				return
			}

			const result = this.transformData(this.list_question.itemIds, this.select_data)
			let params = {
				name: this.list_question.name,
				...result,
				score: result.rightIds.length,
				startTime: this.startTime.valueOf(),
			}
			this.userlist = {
				rightIds: result.rightIds || [],
				errIds: result.errIds || [],
				noneIds: result.noneIds || [],
				score: result.score || 0,
				...params
			}
			this.$refs.submitPopup.open()

			addSubOnePaper(params).then(res => {
				this.id = res.data.id
			})
		},
		getScoreStyle(score) {
			const totalItems = this.list_question?.itemIds?.length || 0
			return {
				'color': (score || 0) < totalItems ? '#f00' : '#329cfe'
			}
		}
	},
	computed: {
		totalItems() {
			return this.list_question?.itemIds?.length || 0
		},
		scoreInfo() {
			return {
				rightCount: this.userlist?.rightIds?.length || 0,
				errorCount: this.userlist?.errIds?.length || 0,
				noneCount: this.userlist?.noneIds?.length || 0,
				totalCount: this.list_question?.itemIds?.length || 0
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.nav-top {
	top: 40px;
}

.scroll-top {
	margin-top: 40rpx;
}

.subject1 {
	.list-box {

		// margin: 0 20rpx;
		// background: #0066ff40;


		.list-public-box {
			padding: 10rpx 20rpx 20rpx 20rpx;
		}

		.list-box-title {

			color: #fff;
			display: inline-block;
			padding: 10rpx 20rpx;
			border-radius: 0 30rpx 0 0;
		}

		.list-li {
			border-radius: 10rpx;
			background: #fff;
			border: 2rpx solid #000;
			margin: 10rpx 0;
			text-align: center;
			overflow: hidden;
			position: relative;


			.img-text {
				font-size: 26rpx;
				display: block;
				background: #c5c5c5;
			}
		}

		.on {
			position: relative;

			&:after {
				position: absolute;
				left: 0;
				top: 0;
				// translate-x: (50%);
				// translate
				content: '';
				width: 100%;
				height: 100%;
				background: #ff000052;
			}
		}
	}

}

.select-box {
	position: fixed;
	width: 100%;
	background-color: #e0e0e0;
	bottom: 0;
	padding-top: 30rpx;
	border-radius: 30rpx 30rpx 0rpx 0rpx;
}

.select-list {

	margin: 0 30rpx 20rpx 20rpx;

	.select-item {
		position: relative;
	}

	.select-img {
		border-radius: 5rpx;
		background: #fff;
		border: 1px solid #333;
		text-align: center;
		position: relative;
	}

	.icon-cuowu1 {
		position: absolute;
		top: -5rpx;
		right: -15rpx;
		color: #f00;
		z-index: 9;
	}
}

.nav {
	display: flex;
	margin: 0 20rpx;

	.nav-list {
		border-radius: 0rpx 0 10rpx 10rpx;
		// border: 1px solid #333;
		font-size: 25rpx;
		font-weight: 700;
		padding: 5rpx 10rpx;
		text-align: center;
		background-color: #333;
		color: #fff;
		width: 25%;
		margin: 0 2rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.on {
		background-color: #2386FFFF;
		color: #fff;
	}
}
.select-box-content{
	width: 100%;
}
.select-title {
	padding-left: 20rpx;
	padding-bottom: 20rpx;
	font-weight: 700;
}

.paper-box {
	background-color: #fff;
	border-radius: 20rpx;
	margin: 0 20rpx;

	.paper-list {
		// margin: 0 10rpx;
		padding: 0 10rpx;
		margin-bottom: 30rpx;
	}

	.btnMin {
		padding: 0 !important;
		width: 10%;
	}


	.submitPopupBtn {
		display: flex;

		.close-btn {
			flex: 1;
		}

		.submit-btn {
			flex: 1;
		}
	}
}

.submitPopupTxt {
	text-align: center;
	padding-bottom: 20rpx;

	.popup-title {
		display: block;
		padding: 10rpx 0;
		font-size: 40rpx;
	}

	.popup-sub {
		display: block;
		padding: 0 20rpx;
		font-size: 35rpx;
	}
}

.submit-popup-box {
	background-color: #fff;
	border-radius: 20rpx;
	margin: 0 20rpx;
	width: 600rpx;

	.submitPopupTxt {}

	.popup-sub {
		padding: 5px 15rpx;
		font-size: 13px;
		border-bottom: 1px dashed #333;
	}

	.submit-name {
		display: block;
	}

	.fraction {
		display: flex;
		justify-content: center;
		align-items: baseline;
		border-bottom: 1px solid #a29f9f;

		.fraction-num {
			font-weight: bold;
			font-size: 68rpx;
		}
	}

	.timePaper {
		display: block;
		font-size: 30rpx;
		padding: 10rpx 0;
		border-bottom: 1px solid #a29f9f;
	}

	.submit-list {
		display: flex;

		.list-btn {
			// flex: 1;
		}
	}

	.prompt-box {
		display: flex;
		justify-content: space-around;
		border-bottom: 1px solid #a29f9f;
		margin-bottom: 30rpx;

		.prompt-box-txt {
			padding: 10rpx 0;
			border-left: 1px solid #a29f9f;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			flex: 1;
		}
	}
}

.subject-list {
	.iconfont {
		position: absolute;
		top: 50%;
		left: 50%;
		font-size: 120rpx;
		color: #fff;
		transform: translate(-50%, -50%);
	}

	.subject-err {
		.iconfont {
			color: #f00;
		}
	}

	.subject-right {
		.iconfont {
			color: #009ff7;
		}
	}
}

.subject-err {
	background-color: #ff00004f;
	position: absolute;
	width: 100%;
	height: 100%;
	left: 0;
	z-index: 3;

}

.subject-right {
	background-color: #009ff773;
	position: absolute;
	width: 100%;
	height: 100%;
	left: 0;
	z-index: 3;
}
</style>